package org.mipt.infsec.steganography.impl.petzib.datastorage;

import java.io.*;
import java.util.*;

/**
 * Class provide some language ability
 */
public class Dictionary
{
    public Map<Integer, ArrayList<org.mipt.infsec.steganography.impl.petzib.datastorage.String>> map = new HashMap<Integer, ArrayList<String>>();

    static Dictionary instance;

    public static Dictionary getInstance() throws Exception
    {
        if (instance == null)
            instance = new Dictionary(Dictionary.class.getResourceAsStream("dictionary.txt"));
        return instance;
    }


    private Dictionary(Reader reader)
    {
        Scanner scanner = new Scanner(reader);
        scanner.useDelimiter("[^а-яА-Я]+");
        while (scanner.hasNext())
        {
            java.lang.String word = scanner.next();
            String string = new String(word.toLowerCase());
            addWordToMap(string);
        }
    }

    private Dictionary(InputStream is) throws Exception
    {
        this(new InputStreamReader(is, "Cp1251"));
    }

    private Dictionary(File file) throws Exception
    {
        this(new FileInputStream(file));
    }

    private void addWordToMap(String string)
    {
        int key = string.hashCode();
        ArrayList<String> set = map.remove(key);
        if (set == null)
        {
            set = new ArrayList<String>();
        }
        set.add(string);
        map.put(key, set);
    }

    public java.lang.String getString(Integer key)
    {
        ArrayList<String> set = map.get(key);
        Random random = new Random(System.currentTimeMillis());
        int index = Math.abs(random.nextInt()) % set.size();
        String string = set.remove(index);
        return string.value;
    }
}
